package cn.hdufocus.focus_helper.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;

import java.util.HashMap;
import java.util.Map;

public class CaptchaUtil {
    private static final String URL = "https://captcha.tencentcloudapi.com/";
    private static final String APP_ID = "2074849171";
    private static final String APP_SECRET_KEY = "01ZZ6zrLs0OZoXSngJ5K-9g**";
    private static final String ACTION = "DescribeCaptchaResult";
    private static final int CAPTCHA_TYPE = 9;
    private static final String VERSION = "2019-07-22";

    public static boolean checkTicket(String ticket, String randStr, String ip) {
        Map<String, Object> parms = new HashMap<String, Object>();
        parms.put("CaptchaType", CAPTCHA_TYPE);
        parms.put("Ticket", ticket);
        parms.put("UserIp", ip);
        parms.put("Randstr", randStr);
        parms.put("CaptchaAppId", APP_ID);
        parms.put("AppSecretKey", APP_SECRET_KEY);
        ObjectMapper objectMapper = new ObjectMapper();
        String params = null;
        try {
            params = objectMapper.writeValueAsString(parms);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return false;
        }
        try {
            Credential cred = new Credential("AKIDHNKEC2IOGxUnw3pf7MRK9nNl1BFMNTVS", "56xeMqOj1ILExVJ7UnIfx0YrxownQt9F");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("captcha.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CaptchaClient client = new CaptchaClient(cred, "ap-shanghai", clientProfile);
            DescribeCaptchaResultRequest req = DescribeCaptchaResultRequest.fromJsonString(params, DescribeCaptchaResultRequest.class);
            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            long code = resp.getCaptchaCode();
            long evil = resp.getEvilLevel();
            if (code == 1 && (evil < 70)) {
                return true;
            } else {
                return false;
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return false;
        }

    }

}
